<!-- Copyright (c) 2014 The Chromium Authors. All rights reserved.
Use of this source code is governed by a BSD-style license that can be
found in the LICENSE file. -->

<link rel="import" href="../common/cr-butterbar.html">
<link rel="import" href="../common/cr-button.html">
<link rel="import" href="../common/cr-dialog.html">
<link rel="import" href="../common/cr-toolbar.html">
<link rel="import" href="cr-issue-editor.html">

<polymer-element name="cr-issue-edit-dialog" attributes="issue">
    <template>
        <link rel="stylesheet" href="../common/common.css">

        <dialog is="cr-dialog" id="dialog" on-cancel="{{ cancel }}">
            <cr-butterbar message="{{ butterbarMessage }}"></cr-butterbar>

            <h1>Edit Issue</h1>

            <cr-issue-editor id="editor" issue="{{ issue }}" errors="{{ errors }}" disabled="{{ saving }}"></cr-issue-editor>

            <cr-toolbar>
                <button is="cr-button" primary on-tap="{{ save }}">Save</button>
                <button is="cr-button" on-tap="{{ cancel }}">Cancel</button>
            </cr-toolbar>
        </dialog>
    </template>
    <script>
        Polymer({
            created: function() {
                this.issue = null;
                this.errors = {};
                this.butterbarMessage = "";
                this.saving = false;
            },
            cancel: function(event) {
                if (this.$.editor.dismissAutocomplete()) {
                    event.preventDefault();
                    return;
                }
                this.close();
            },
            reset: function() {
                this.saving = false;
                this.butterbarMessage = "";
                this.errors = {};
                this.$.editor.dismissAutocomplete();
            },
            close: function() {
                this.reset();
                this.$.dialog.close();
            },
            save: function() {
                var data = this.$.editor.createEditData();
                this.saving = true;
                this.butterbarMessage = "Saving...";
                this.issue.edit(data)
                    .then(this.saveSuccess.bind(this))
                    .catch(this.saveFailure.bind(this));
            },
            saveSuccess: function() {
                this.fire("issue-refresh");
                this.close();
            },
            saveFailure: function(error) {
                this.reset();
                if (!error.fieldName) {
                    // TODO(esprehn): Show a better error message, deal with network errors.
                    return;
                }
                this.errors[error.fieldName] = error.message;
            },
            showModal: function() {
                if (!this.issue)
                    return;
                this.$.editor.reset();
                this.$.dialog.showModal();
            },
        });
    </script>
</polymer-element>
